﻿
function addnewledadvwin(sssidarray,advaddressarray,editrecord){
    /******sssidarray 编辑后写入的trackerid (确定是否编辑框)
            advaddressarray 对应advaddress
            ledadvid窗口打开默认载入的广告
    *******************************/
    function msgUpdateSuccess() {
        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
        Ext.Msg.show({
            title: _TrackerMain_Title,
            msg: _NewForText_Success,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.INFO
        });
    }
    
    function msgWarning(msgtext) {
        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
        Ext.Msg.show({
            title: _TrackerMain_Title,
            msg: msgtext,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }
    
    function msgUpdateFailure() {
        Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
        Ext.Msg.show({
            title: _TrackerMain_Title,
            msg: _NewForText_Failure,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }
    
    function createNewParam(paramfieldtype, captext, maxlen, unittext, cmbstore,name,id) {
        var r;
        if (unittext.length == 0)
            unittext = " "; //give a space if text is empty
        var lblunit = createNewParamUnitLabel(unittext);
        if (paramfieldtype == EnumParamFieldType.TextField)
            r = createNewParamTextField(captext, maxlen,false,null,name);
        else if (paramfieldtype == EnumParamFieldType.NumberField)
            r = createNewParamNumberField(captext, maxlen);
        else if (paramfieldtype == EnumParamFieldType.ComboBoxField) {
            r = createNewParamCmbField(cmbstore, captext);
            r.setValue(cmbstore.getAt(0).get(r.valueField));
        }
        else if (paramfieldtype == EnumParamFieldType.MultiComboBoxField) {
            r = createNewMultiParamCmbField(cmbstore, captext);
        }
        else if (paramfieldtype == EnumParamFieldType.TextArea) {
            r = createNewParamTextArea(captext, maxlen);
        }
        else if(paramfieldtype == EnumParamFieldType.Date){
            r = createNewParamDate(captext,false,id);
        }
        else if(paramfieldtype == EnumParamFieldType.Time){
            r = createNewParamTime(captext,false,id);
            r.setWidth(100);
        }
        if (!Ext.isEmpty(name))
            r.name = name;
        return r;
    }

    var trackNameCombo = getTrackerCheckboxCombo(true);
    if(Ext.isDefined(sssidarray)){
        //如果是编辑，不需要再选设备
        trackNameCombo.setVisible(false);
    }
    
    trackNameCombo.labelStyle='padding-top:6px;padding-left:10px;text-align:left';
    trackNameCombo.fieldLabel = _ImageButtonText_TrackerName + "(" + _TrackerMain_NoSelectionMeansAll + ")";
    var txtAdvname = createNewParam(EnumParamFieldType.TextField, _LED_AdvName, 255, "", null);
    var stofont = new Ext.data.ArrayStore({
        fields: [{name:'valueid',type:'integer'}, 'val'],
        data: [[0,_LED_Font_Sim],[1,_LED_Font_Blod]]//,[2,_LED_Font_Song],[3,_LED_Font_Hei],[4,_LED_Font_Kai],[5,_LED_Font_XinSong]]
    });
    var cmbfont = createNewParam(EnumParamFieldType.ComboBoxField, _LED_Font, 0, "", stofont);
    var stocolor = new Ext.data.ArrayStore({
        fields: [{name:'valueid',type:'integer'}, 'val'],
        data: [[1,_Color_Red],[2,_Color_Yellow],[3,_Color_Green],[4,_Color_AntiRed],[5,_Color_AntiYellow]]
    });
    var cmbcolor = createNewParam(EnumParamFieldType.ComboBoxField, _Color, 0, "", stocolor);
    var stomove = new Ext.data.ArrayStore({
        fields: [{name:'valueid',type:'integer'}, 'val'],
        data: [[1,_LED_MoveLeft],[3,_LED_MoveUp],[4,_LED_MoveDown],[5,_LED_Keep]]//[2,_LED_MoveRight],
    });
    var cmbmoving = createNewParam(EnumParamFieldType.ComboBoxField, _LED_MoveDirection, 0, "", stomove);
    var stospeed = new Ext.data.ArrayStore({
        fields: [{name:'valueid',type:'integer'}, 'val'],
        data: [[0,_LED_Speed0],[1,_LED_Speed1],[2,_LED_Speed2],[3,_LED_Speed3],[4,_LED_Speed4]]
    });
    var cmbspeed = createNewParam(EnumParamFieldType.ComboBoxField,_LED_Speed, 0, "", stospeed);
    var txtkeeptime = createNewParam(EnumParamFieldType.NumberField,_LED_KeepTime, 3, _TrackerMain_Second, null);
    txtkeeptime.setMaxValue(255);
    txtkeeptime.setMinValue(0);
    txtkeeptime.setValue(0);
    var stostoptype= new Ext.data.ArrayStore({
        fields: [{name:'valueid',type:'integer'}, 'val'],
        data: [[0,_LED_StopModel1],[1,_LED_StopModel2]]
    });
    var cmbstopmodel = createNewParam(EnumParamFieldType.ComboBoxField, _LED_StopModel, 0, "", stostoptype);

    //var txtshowtimespan = createNewParam(EnumParamFieldType.NumberField, _LED_MessageShowTime, 255, _TrackerMain_Second, null);
    var txtshowtimes = createNewParam(EnumParamFieldType.NumberField, _LED_ShowTimes, 3, "", null);
    txtshowtimes.setValue(1);
    txtshowtimes.setMinValue(1);
    txtshowtimes.setMaxValue(255);
    var txtadvstartdate = createNewParam(EnumParamFieldType.Date, _LED_StartDate, 0, "", null, 'advstartdate');

    txtadvstartdate.setDisabled(true);
    var txtadvstopdate= createNewParam(EnumParamFieldType.Date,_LED_StopDate,0,"",null,'advstopdate');
    txtadvstopdate.setDisabled(true);
    var txtBody = createNewParam(EnumParamFieldType.TextArea, _LED_Body, 128, "", null);
    txtBody.addListener('change', function(obj, newValue, oldValue) {
        if (isUnicode(newValue))
            txtBody.maxLength = 128;
        else
            txtBody.maxLength = 256;
    });
    
    var chkAllLife = new Ext.form.Checkbox({
        fieldLabel:_LED_AllLife,
        labelStyle: 'padding-top:6px;padding-left:10px;text-align:left'
    });
    chkAllLife.setValue(true);
    
    chkAllLife.addListener('check', function(obj, check) {
        if (check) {
            txtadvstartdate.setDisabled(true);
            txtadvstartdate.allowBlank = true;
            txtadvstopdate.setDisabled(true);
            txtadvstopdate.allowBlank = true;
        }
        else {
            txtadvstartdate.setDisabled(false);
            txtadvstartdate.allowBlank = false;
            txtadvstopdate.setDisabled(false);
            txtadvstopdate.allowBlank = false;
        }
    });
    
    var btnAddNewTimeSpan= new Ext.Button({
        text: _LED_AddTimeSpan,
        handler: function(){
            var panelTimespans = addnewledadvform.find('name','pantimespan');
            var timebegins = addnewledadvform.find('name', 'timebegin');
            if(timebegins.length >= 24){
                btnAddNewTimeSpan.setDisabled(true);
                
            }
            else{
                btnAddNewTimeSpan.setDisabled(false);
                btnRemoveTimeSpan.setDisabled(false);
            }
            var timebegin = createNewParam(EnumParamFieldType.Time, _LED_StartTimeSpan, 0, "", null, "timebegin");
            var timeend = createNewParam(EnumParamFieldType.Time, _LED_StopTimeSpan, 0, "", null, "timeend");
            
            var pantimspan = new Ext.Panel({
                labelStyle: 'padding-top:6px;padding-left:10px;text-align:left',
                border:false,
                fieldLabel:_LED_TimeSpan,
                layout: 'column',
                name:'pantimespan',
                items:[timebegin,timeend]
            });
            addnewledadvform.add(pantimspan);
            txtshowtimes.setValue(0);
            txtshowtimes.setDisabled(true);
            addnewledadvform.doLayout();
        }
    });
    
    var btnRemoveTimeSpan = new Ext.Button({
        text: _LED_RemoveTimeSpan,
        disabled: true,
        handler: function() {
            var panelTimespans = addnewledadvform.find('name','pantimespan');
            var timebegins = addnewledadvform.find('name', "timebegin");
            var timeends = addnewledadvform.find('name', "timeend");
            if (timebegins.length == 1){
                this.setDisabled(true);
                btnAddNewTimeSpan.setDisabled(false);
                txtshowtimes.setDisabled(false);
            }
            var lastpaneltimespan =  panelTimespans[panelTimespans.length-1];
            var lasttimebegin= timebegins[timebegins.length - 1];
            var lasttimeend = timeends[timeends.length-1];
            lastpaneltimespan.remove(lasttimebegin);
            lastpaneltimespan.remove(lasttimeend);
            addnewledadvform.remove(lastpaneltimespan, true);
            
            
            Ext.destroy(lasttimebegin);
            Ext.destroy(lasttimeend);
            Ext.destroy(lastpaneltimespan);
            addnewledadvform.doLayout();
        }
    });

    var addnewledadvform = new Ext.form.FormPanel({
        bodyStyle: "padding-top:10px",
        width: 380,

        height: 680,
        defaultType: "textfield",
        autoScroll: true,
        items: [
            trackNameCombo,
            txtAdvname,
            cmbfont,
            cmbcolor,
            cmbmoving,
            cmbspeed,
            txtkeeptime,
            cmbstopmodel,
            txtshowtimes,
            chkAllLife,
            txtadvstartdate,
            txtadvstopdate,
            txtBody
        ],
        buttons: [btnAddNewTimeSpan,
        btnRemoveTimeSpan,
        { text: _CustomerConfigResource_Save,
            handler: function() {
                if (addnewledadvform.getForm().isValid()) {
                    Ext.MessageBox.show({
                        msg: _NewForText_Saving,
                        progressText: _NewForText_Saving + '...',
                        width: 300,
                        wait: true,
                        waitConfig: { interval: 200 },
                        icon: 'download'
                    });
                    var timebegins = addnewledadvform.find('name', "timebegin");
                    var timeends = addnewledadvform.find('name', "timeend");
                    var stime = "";
                    var i;
                    for (i = 0; i < timebegins.length; i++) {
                        stime += (stime == "" ? "" : ",") + timebegins[i].getValue() + "," + timeends[i].getValue();
                    }
//                    var charlen = sumStr(txtBody.getValue());
//                    var screenlen = 16; //
//                    var direction = cmbmoving.getValue();
//                    var speed = getChuanJiCharSpeed(cmbspeed.getValue());
//                    var stoptime = cmbstopmodel.getValue();
//                    var keeptime = getChuanJiLEDShowTime(charlen, screenlen, direction, speed, stoptime);
                    if (Ext.isDefined(sssidarray)) {
                        //edit
                        var sssids = "";
                        var advaddresses = "";
                        var i;
                        for (i = 0; i < sssidarray.length; i++) {
                            sssids += (sssids.length == 0 ? "" : ",") + sssidarray[i].toString();
                            advaddresses += (advaddresses.length == 0 ? "" : ",") + advaddressarray[i].toString();
                        }
                        Ext.Ajax.request({
                            url: "HandlerLEDAdv",
                            method: "POST",
                            timeout:120000,
                            params: {
                                event: "edit",
                                sssids: sssids,
                                advaddresses: advaddresses,
                                advname: txtAdvname.getValue(),
                                fontindex: cmbfont.getValue(),
                                colorindex: cmbcolor.getValue(),
                                movingindex: cmbmoving.getValue(),
                                speedindex: cmbspeed.getValue(),
                                keeptime: txtkeeptime.getValue(),
                                stopmodel: cmbstopmodel.getValue(),
                                showtimes: txtshowtimes.getValue(),
                                usealllife: chkAllLife.getValue(),
                                advstartdate: txtadvstartdate.getValue(),
                                advstopdate: txtadvstopdate.getValue(),
                                body: txtBody.getValue(),
                                timespans: stime
                            },
                            success: function(result) {
                                //after success
                                Ext.MessageBox.hide();
                                var flag = result.responseText;
                                if (flag == 'true') {
                                    msgUpdateSuccess();
                                }
                                else {
                                    var nosuccesstrackername = "";
                                    var tmpsssids = flag.split(',');
                                    trackNameCombo.store.each(function(record) {
                                        var i;
                                        for (i = 0; i < tmpsssids.length; i++) {
                                            if (record.get('sssid') == tmpsssids[i]) {
                                                nosuccesstrackername = (nosuccesstrackername == "" ? "" : ",") + record.get('trackername');
                                            }
                                        }
                                    });
                                    msgWarning(nosuccesstrackername + _LED_AdvAddFailed);
                                }
                                g_LEDWindowObject.searchLEDAdv();

                            },
                            failure: function(form, action) {
                                msgUpdateFailure();
                            }
                        });
                    }
                    else {
                        //add new
                        Ext.Ajax.request({
                            url: "HandlerLEDAdv",
                            method: "POST",
                            timeout: 120000,
                            params: {
                                event: "addnewledadv",
                                sssids: trackNameCombo.getValue(),
                                advname: txtAdvname.getValue(),
                                fontindex: cmbfont.getValue(),
                                colorindex: cmbcolor.getValue(),
                                movingindex: cmbmoving.getValue(),
                                speedindex: cmbspeed.getValue(),
                                keeptime: txtkeeptime.getValue(),
                                stopmodel: cmbstopmodel.getValue(),
                                showtimes: txtshowtimes.getValue(),
                                usealllife: chkAllLife.getValue(),
                                advstartdate: txtadvstartdate.getValue(),
                                advstopdate: txtadvstopdate.getValue(),
                                body: txtBody.getValue(),
                                timespans: stime
                            },
                            success: function(result) {
                                //after success
                                Ext.MessageBox.hide();
                                var flag = result.responseText;
                                if (flag == 'true') {
                                    msgUpdateSuccess();
                                }
                                else {
                                    var nosuccesstrackername = "";
                                    var tmpsssids = flag.split(',');
                                    trackNameCombo.store.each(function(record) {
                                        var i;
                                        for (i = 0; i < tmpsssids.length; i++) {
                                            if (record.get('sssid') == tmpsssids[i]) {
                                                nosuccesstrackername = (nosuccesstrackername == "" ? "" : ",") + record.get('trackername');
                                            }
                                        }
                                    });
                                    msgWarning(nosuccesstrackername + _LED_AdvAddFailed);
                                }

                            },
                            failure: function(form, action) {
                                msgUpdateFailure();
                            }
                        });
                    }
                }
            }
}]
        });
        
    var addnewledadvwin = new Ext.Window({
        height: 610,
        closeAction: 'hide',
        width: 400,
        plain: true,
        modal: 'true',
        buttonAlign: "center",
        constrain:true,
        layout: 'fit',
        title: _LED_AddAdv,
        items: [addnewledadvform]
    });
    
    if(Ext.isDefined(sssidarray)){
        addnewledadvwin.setTitle(_LED_AdvEdit);
    }

    addnewledadvform.addListener('afterrender', function() {
        if (Ext.isDefined(editrecord)) {
            addnewledadvwin.setTitle(editrecord.get('trackername') + " " + _LED_MailboxNumber + editrecord.get('adv_address'));
            txtAdvname.setValue(editrecord.get('advname'));
            cmbfont.setValue(editrecord.get('font'));
            cmbcolor.setValue(editrecord.get('color'));
            cmbmoving.setValue(editrecord.get('moving'));
            cmbspeed.setValue(editrecord.get('speed'));
            cmbstopmodel.setValue(editrecord.get('stop_model'));
            txtkeeptime.setValue(editrecord.get('stay_time'));
            chkAllLife.setValue(editrecord.get('usealllife'));
            txtshowtimes.setValue(editrecord.get('showtimes'));
            txtadvstartdate.setValue(editrecord.get('start_date'));
            txtadvstopdate.setValue(editrecord.get('stop_date'));
            txtBody.setValue(editrecord.get('text'));
            var tmp;
            if (editrecord.get('timespans').indexOf(',') != -1)
                tmp = editrecord.get('timespans').split(',');
            else
                tmp = editrecord.get('timespans').split('|');
            if (editrecord.get('timespans').length > 0) {
                var i;
                var hasTimeSpan = false;
                for (i = 0; i < tmp.length; i++) {
                    var t = tmp[i].split('-');
                    var timebegin = createNewParam(EnumParamFieldType.Time, _LED_StartTimeSpan, 0, "", null, "timebegin");
                    var timeend = createNewParam(EnumParamFieldType.Time, _LED_StopTimeSpan, 0, "", null, "timeend");

                    var pantimspan = new Ext.Panel({
                        labelStyle: 'padding-top:6px;padding-left:10px;text-align:left',
                        border: false,
                        fieldLabel: _LED_TimeSpan,
                        layout: 'column',
                        name: 'pantimespan',
                        items: [timebegin, timeend]
                    });
                    addnewledadvform.add(pantimspan);
                    hasTimeSpan = true;
                    timebegin.setValue(t[0]);
                    timeend.setValue(t[1]);
                }
                if (hasTimeSpan) {
                    txtshowtimes.setValue(0);
                    txtshowtimes.setDisabled(true);
                    btnAddNewTimeSpan.setDisabled(true);
                    btnRemoveTimeSpan.setDisabled(false);
                }
                addnewledadvform.doLayout();
            }
        }
    });

    addnewledadvwin.show();
    cmbcolor.setVisible(false);
    addnewledadvwin.addListener('afterrender', function() {
        cmbcolor.setVisible(false);
    });
}